package com.banmao.youZone.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.banmao.youZone.consts.CommonConst;
import com.banmao.youZone.entity.TaskTrigger;
import com.banmao.youZone.entity.UserVO;
import com.banmao.youZone.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class OnceJob extends QuartzJobBean {

    @Resource
    private UserMapper userMapper;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        DateTime currentTime = DateUtil.date();
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        int userId = jobDataMap.getInt(CommonConst.USER_ID);
        log.info("[JOB单次任务]执行:{},userId:{}", currentTime, userId);

        UserVO userVO = userMapper.selectById(userId);

        if (!userVO.getExecuteJob()) {
            log.info("[JOB日常任务]userId:{}未开启定时打卡", userId);
            return;
        }

        Trigger trigger = context.getTrigger();

        JobDataMap triggerDataMap = trigger.getJobDataMap();
        Object taskJson = triggerDataMap.get(CommonConst.TASK_JSON);
        if (!(taskJson instanceof String)) {
            log.error("[JOB单次任务]异常触发，没有携带任务信息");
            return;
        }

        TaskTrigger taskTrigger = JSON.parseObject((String) taskJson, TaskTrigger.class);

        log.info("[JOB单次任务]执行taskTrigger:{}", taskJson);

        taskTrigger.setPredictExecuteTime(DateUtil.date());
        ExecuteClockJob.addTask(taskTrigger);

    }

}
